package org.example.mutithread.reentrantrwlock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Product {

    private String name;
    private String type;

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    private Condition rc = readLock.newCondition();
    private Condition wc = writeLock.newCondition();

    private volatile boolean flag = false;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void produce(String name, String type) {
        if (flag) {
            try {
                readLock.lock();
                // System.out.println("----pc.await()");
                rc.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }
        }
        try {
            // lock.lock();
            this.setName(name);
            this.setType(type);
            System.out.println("生产了：" + this.toString());
            flag = true;
            // cc.signal();
        } finally {
            // lock.unlock();
        }

    }

    public void consume() {

        if (!flag) {
            try {
                // lock.lock();
                // System.out.println("---cc.await()");
                // cc.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // lock.unlock();
            }
        }
        try {
            // lock.lock();
            System.out.println("消费了：" + this.toString());
            flag = false;
            // pc.signal();
        } finally {
            // lock.unlock();
        }

    }

    @Override
    public String toString() {
        return "Product{" + "name='" + name + '\'' + ", type='" + type + '\'' + '}';
    }
}
